package com.our.shop.system.util;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;



public class DateUtil {
	private static SimpleDateFormat df = new SimpleDateFormat();
	/**
	 * 将Date对象转换成指定格式的String字符
	 * date：时间对象，partten：时间格式字符串
	 * */
	public static String date2Str(Date date, String partten) {
		String result = null;
		df.applyPattern(partten);
		result = df.format(date);
		return result;
	}
	/**
	 * 将Date字符串转换成指定格式的Date对象
	 * dateStr：时间字符串（2015/09/11），partten：时间格式字符串（yyyy/MM/dd） （必须与时间字符串格式一致）
	 * @throws ParseException 
	 * */
	public static Date str2Date(String dateStr, String pattern) throws ParseException {
		Date date = null;
		df.applyPattern(pattern);
		date = df.parse(dateStr);
		return date;
	}
	/**
	 * 获取某月的第一天与最后一天
	 * month：想要获取的月份
	 * */
	public static Map<String, String> getMonthLastAndFirst(int month) {
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");

		GregorianCalendar gcLast = (GregorianCalendar) Calendar.getInstance();
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(new Date());

		calendar.add(2, -month);
		Date theDate = calendar.getTime();
		gcLast.setTime(theDate);
		gcLast.set(5, 1);
		String monthFirstDay = df.format(gcLast.getTime());
		StringBuffer str = new StringBuffer().append(monthFirstDay).append(" 00:00:00");
		monthFirstDay = str.toString();

		calendar.add(2, 1);
		calendar.set(5, 1);
		calendar.add(5, -1);
		String monthLastDay = df.format(calendar.getTime());
		StringBuffer endStr = new StringBuffer().append(monthLastDay).append(" 23:59:59");
		monthLastDay = endStr.toString();

		Map<String, String> map = new HashMap<String, String>();
		map.put("monthFirstDay", monthFirstDay);
		map.put("monthLastDay", monthLastDay);
		return map;
	}
	/**
	 * 获取近10年年份
	 * */
	public static List<String> getBeforeTenYears() {
		List<String> list = new ArrayList<String>();
		for (int i = 0; i < 11; ++i) {
			Calendar c = Calendar.getInstance();
			c.add(1, -i);
			DateFormat df = new SimpleDateFormat("yyyy");
			list.add(df.format(c.getTime()));
		}
		return list;
	}
	/**
	 * 获取当前年年份
	 * */
	public static String getThisYears() {
		Calendar c = Calendar.getInstance();
		c.add(1, 0);
		DateFormat df = new SimpleDateFormat("yyyy");
		return df.format(c.getTime());
	}
	/**
	 * 获取当前月
	 * */
	public static String getThisMoth() {
		Date dt = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String date = sdf.format(dt);
		return date;
	}
	/**
	 * 获取当前月第一天，按指定格式返回
	 * partten（返回时间格式）
	 * */
	public static String getMonthFirstDay(String partten) {
		Calendar calendar = Calendar.getInstance();
		calendar.set(5, calendar.getActualMinimum(5));
		SimpleDateFormat sdf = new SimpleDateFormat(partten);
		return sdf.format(calendar.getTime());
	}
	/**
	 * 获取当前月最后一天，按指定格式返回
	 * partten（返回时间格式）
	 * */
	public static String getMonthLastDay(String partten) {
		Calendar calendar = Calendar.getInstance();
		calendar.set(5, calendar.getActualMaximum(5));
		SimpleDateFormat sdf = new SimpleDateFormat(partten);
		return sdf.format(calendar.getTime());
	}
	/**
	 * 获取前一天，按指定格式返回
	 * partten（返回时间格式）
	 * */
	public static String getYesterday(String partten) {
		Calendar calendar = Calendar.getInstance();
		calendar.add(5, -1);
		SimpleDateFormat sdf = new SimpleDateFormat(partten);
		return sdf.format(calendar.getTime());
	}
	/**
	 * 获取前日期时间，按指定格式返回
	 * partten（返回时间格式）
	 * */
	public static String getDateTime(String partten) {
		Date dt = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat(partten);
		String date = sdf.format(dt);
		return date;
	}
	/**
	 * 获取前时间
	 * */
	public static String getThisTime() {
		Date dt = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
		String date = sdf.format(dt);
		return date;
	}
	/**
	 * 判断某一个时间是否在开始之前并且在结束时间之后（是否在俩个时间之间）
	 * startDate：开始时间，endDate结束时间，date 
	 * */
	public static boolean betweenDate(String startDate, String endDate,String date) {
		int result = date.compareTo(startDate);
		int result2 = date.compareTo(endDate);
		if (result < 0) {
			return false;
		}
		return (result2 <= 0);
	}
	/**
	 * 获取本周开始时间
	 * */
	public static String getWeekStartDate() {
		String result = null;
		Calendar calendar = Calendar.getInstance(TimeZone.getDefault());
		calendar.add(5, 0);
		while (1 != calendar.get(7)) {
			calendar.add(5, -1);
		}
		int startDayInt = calendar.get(5);
		String startDay = padZero(startDayInt);
		int startMonthInt = calendar.get(2) + 1;
		String startMonth = padZero(startMonthInt);
		result = calendar.get(1) + "-" + startMonth + "-" + startDay;

		return result;
	}
	/**
	 * 获取本周结束时间
	 * */
	public static String getWeekEndDate() {
		String result = null;
		Calendar calendar = Calendar.getInstance();
		calendar.add(5, 0);
		while (1 != calendar.get(7)) {
			calendar.add(5, -1);
		}

		calendar.add(5, 6);
		int endDayInt = calendar.get(5);
		String endDay = padZero(endDayInt);
		int endMonthInt = calendar.get(2) + 1;
		String endMonth = padZero(endMonthInt);
		result = calendar.get(1) + "-" + endMonth + "-" + endDay;
		return result;
	}
	private static String padZero(int value) {
		String result = "";
		if ((value < 10) && (value > 0))
			result = "0" + value;
		else {
			result = value+"";
		}
		return result;
	}
	/**
	 * 俩个时间比较
	 * */
	public static boolean compareDate(String date1, String date2)
			throws ParseException {
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd");

		Date dt1 = df.parse(date1);
		Date dt2 = df.parse(date2);
		if (dt1.getTime() > dt2.getTime()) {
			return true;
		}
		return (dt1.getTime() >= dt2.getTime());
	}
	
	/**
	 * 比较2个时间的先后
	 * @param source 待比较的时间。target
	 * @return 当 source在target之前= true, else false
	 */
	public static boolean compare(Date source, Date target){
		return source.before(target);
	}
	public static boolean compare(String source, String target) throws ParseException{
		Date s = df.parse(source);
		Date t = df.parse(target);
		return s.before(t);
	}
	/**
	 * 求2个时间段之间的间隔
	 * @param bdate
	 * @param edate = "" or null时间， edate的值为目前时间
	 * @param type = 1时表示两时间段间的天数, type = 2时表示两时间段间的小时数 type = 3时表示两时间段间的分钟数
	 * @return
	 */
	public static long getDateLong(String bdate,String edate,int type){
		if(bdate == null || bdate.equals("")) return 0L;
		long result = 0L;
		try {
			long bt =  df.getCalendar().getTimeInMillis();
			long et = 0L;
			if(edate != null && !edate.equals("")){
				df.parse(edate);
				et =  df.getCalendar().getTimeInMillis();
			}else{
				et = Calendar.getInstance().getTimeInMillis();//当天
			}
			switch(type){
				case 1:
					result =  ((et-bt)/(1000*60*60*24));
					break;
				case 2:
					result =  ((et-bt)/(1000*60*60));
					break;
				case 3:
					result =  ((et-bt)/(1000*60));
					break;
			}
		} catch (ParseException e) {
			e.printStackTrace();
			return 0L;
		}
		return result;
	}
	/**
	 * 求2个时间段之间的间隔
	 * @param bdate
	 * @param edate = "" or null时间， edate的值为目前时间
	 * @param type = 1时表示两时间段间的天数, type = 2时表示两时间段间的小时数 type = 3时表示两时间段间的分钟数
	 * @return
	 */
	public static long getDateLong(Date bdate,Date edate,int type){
		if(bdate == null) return 0L;
		return edate == null?getDateLong(df.format(bdate),null,type):getDateLong(df.format(bdate),df.format(edate),type);
	}
	/**
	 * 计算 time 的下n天
	 * @param time
	 * @return
	 */
	public static String nextDate(String time,int nday){
		Calendar now_Time = Calendar.getInstance();
        DateFormat df=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            now_Time.setTime(df.parse(time));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        now_Time.add(Calendar.DATE,nday);
        SimpleDateFormat sdNowDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sdNowDate.format(now_Time.getTime());
	}
	/**
	 * 时间运算，
	 * 如某时间经过多少分或多少天后的时间
	 *  某时间前几分或几小时或几天的时间 
	 * @param time
	 * @param calcuate  计算数
	 * @param type 计算类型，0:分为单位;1:时为单位;2天为单位;3月为单位
	 * @param addOrdec;运算类型 1:加 ; 2:减 该参数咱不支持，
	 * @return 返回的日期格式是
	 */
	public static String nextDate(String time,int calcuate,int type,int addOrdec){
		Calendar now_Time = Calendar.getInstance();
        DateFormat df=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            now_Time.setTime(df.parse(time));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        if(addOrdec == 2)
        	calcuate = 0-calcuate;
        switch(type){
        	case 0:
        		now_Time.add(Calendar.MINUTE, calcuate);
        		break;
        	case 1:
        		now_Time.add(Calendar.HOUR_OF_DAY, calcuate);
        		break;
        	case 2:
        		now_Time.add(Calendar.DATE,calcuate);
        		break;
        	case 3:
        		now_Time.add(Calendar.MONTH, calcuate);
        		break;
        }
        SimpleDateFormat sdNowDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sdNowDate.format(now_Time.getTime());
	}
	/**
	 * 获取今天是星期几 星期天=1...星期六=7
	 * @param d
	 * @return
	 */
	public static int todayIsWeek(Date d){
		if(d == null)
			d= new Date();
		Calendar c = Calendar.getInstance();
		c.setTime(d);
		return c.get(Calendar.DAY_OF_WEEK);
	}
}